package com.tomshushu.doc.freedoc.core.config;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.tomshushu.doc.freedoc.core.properties.IgnoreUrlsProperties;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Log4j2
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Resource
    private IgnoreUrlsProperties ignoreUrlsProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册 Sa-Token 拦截器，仅负责认证校验（不处理响应）
        registry.addInterceptor(new SaInterceptor(handler -> {
            SaRouter.match("/**")
                    .notMatch(ignoreUrlsProperties.getUrls())
                    .notMatch(HttpMethod.OPTIONS.name())
                    .check(r -> {
                        // 手动检查登录状态并抛出异常（测试用）
                        if (!StpUtil.isLogin()) {
                             log.info("未登录，请先登录");
                        }
                    });
        })).addPathPatterns("/**");
    }
}